package com.gientech.lock2.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * com.gientech.producer.controller
 *
 * @author: Hero
 * @version: 1.0
 * @date: 2023/2/18
 * @ApiNote: 占用分布式锁的用户01
 * TODO
 **/
@RestController
public class OperationLock02 {

    @Resource
    RedisTemplate redisTemplate;
    //    分布式锁键,实现竞争
    final String LOCK_KEY01= "lock01";
    //    分布式锁键，实现占用与释放
    final String LOCK_KEY02= "lock02";

    /**
     * 实现竞争
     */
    @GetMapping("/have")
    public String haveLock(){
        boolean flag = redisTemplate.opsForValue().setIfAbsent(LOCK_KEY01, "user01");
        if (flag){
            return "竞争成功";
        }
        return "竞争失败";
    }

    @GetMapping("/time")
    public String timeLock(){
        return getLock();
    }
    /**
     * 占用锁并写入自己用户名，设置过期时间；判断键值是否属于自己，若属于则显示正在占用，若不属于则等待
     */
    public String getLock(){
        boolean flag = redisTemplate.opsForValue().setIfAbsent(LOCK_KEY02, "user02", 10, TimeUnit.SECONDS);
        if (redisTemplate.opsForValue().get(LOCK_KEY02).equals("user02")){
            return "正在占用";
        }
        return "等待锁";
    }
}
